import { Component, ComponentInterface, Event, EventEmitter, Host, Method, State, h } from '@stencil/core';
import { setUrlQuery } from 'qx-util';
import { IBzPluginIframeController } from './ibz-plugin-iframe-controller';

/**
 * 插件模式iframe承载交互组件
 *
 * @export
 * @class IframeWrapper
 */
@Component({
    tag: 'ibz-plugin-iframe-wrapper',
    styleUrl: 'ibz-plugin-iframe-wrapper.scss',
    shadow: true,
})
export class IBzPluginIframeWrapper implements ComponentInterface {
    /**
     * iframe实例
     *
     * @type {HTMLIFrameElement}
     * @memberof PluginIframeWrapper
     */
    iframe!: HTMLIFrameElement;

    /**
     * iframe呈现指定url
     *
     * @type {string}
     * @memberof PluginIframeWrapper
     */
    @State()
    url?: string;

    /**
     * 事件
     *
     * @type {EventEmitter<any>}
     * @memberof IBzPluginIframeWrapper
     */
    @Event({ eventName: 'closeIframe' })
    closeIframe: EventEmitter<any>;

    /**
     * 事件
     *
     * @type {EventEmitter<any>}
     * @memberof IBzPluginIframeWrapper
     */
    @Event({ eventName: 'hiddenIframe' })
    hiddenIframe: EventEmitter<any>;

    /**
     * iframe加载完毕
     *
     * @type {EventEmitter<any>}
     * @memberof IBzPluginIframeWrapper
     */
    @Event({ eventName: 'iframeLoaded' })
    iframeLoaded: EventEmitter<any>;

    componentDidLoad(): void {
        this.iframe.onload = () => {
            this.loaded();
        };
        (this.iframe.contentWindow as any).iBizPluginIframe = new IBzPluginIframeController(this);
    }

    /**
     * 向iframe发送消息
     *
     * @param {*} [data={}]
     * @return {*}  {Promise<void>}
     * @memberof IBzPluginIframeWrapper
     */
    @Method()
    async sendIframeMessage(data: any = {}): Promise<void> {
        this.iframe.contentWindow.postMessage(JSON.stringify(data), '*');
    }

    /**
     * 加载完毕
     *
     * @memberof IBzPluginIframeWrapper
     */
    loaded = (): void => {
        this.iframeLoaded.emit();
    };

    render() {
        return (
            <Host class='plugin-iframe-wrapper'>
                <iframe ref={ref => (this.iframe = ref)} class='plugin-iframe' src={this.url} />
            </Host>
        );
    }

    /**
     * 获取iframe实例
     *
     * @return {*}  {Promise<HTMLIFrameElement>}
     * @memberof PluginIframeWrapper
     */
    @Method()
    async getIframe(): Promise<HTMLIFrameElement> {
        return this.iframe;
    }

    /**
     * 设置url
     *
     * @param {string} url
     * @param {*} [_params]
     * @memberof IBzPluginIframeWrapper
     */
    @Method()
    async setUrl(url: string, params?: any) {
        this.url = setUrlQuery(url, params);
    }
}
